package cn.damong.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import cn.damong.service.response.ServiceResponse;
import cn.damong.service.weixin.IWeixinService;
import cn.damong.utils.common.JsonUtil;
import cn.damong.weixin.mp.WeixinAuthType;
import cn.damong.weixin.mp.WeixinUserInfo;

/**
 * 微信公众平台控制器
 * 
 * @author CodingPanda
 * @2019年5月10日 上午12:54:00
 *
 */
@Controller
@RequestMapping(value = "/weixin")
public class WeixinController {
    private Logger logger = LoggerFactory.getLogger(WeixinController.class);

    @Autowired
    private IWeixinService weixinService;

    /**
     * 统一微信授权链接，自动拼接并转向微信授权链接
     * 
     * @param request
     * @param response
     * @param type
     *            授权类型
     * @return
     */
    @RequestMapping(value = "/auth", method = RequestMethod.GET)
    public ModelAndView auth(HttpServletRequest request, HttpServletResponse response, String authType) {
        try {
            WeixinAuthType weixinAuthType = WeixinAuthType.fromString(authType);
            if (null == weixinAuthType) {
                weixinAuthType = WeixinAuthType.BASE;
            }

            if (logger.isTraceEnabled()) {
                logger.trace("Cookies:{}", JsonUtil.obj2Json(request.getCookies()));
            }

            response.sendRedirect(weixinService.getAuthUrl(weixinAuthType));
        } catch (IOException e) {
            return new ModelAndView("500");
        } catch (Exception e) {
            logger.error("weixin auth exception:", e);
        }
        return new ModelAndView("500");
    }

    /**
     * 统一微信授权回调地址
     * 
     * @param request
     * @param response
     * @param code
     *            授权码，可以根据授权码获取用户信息
     * @param state
     *            授权类型，只能为snsapibase(获取openid)或者snsapiuserinfo(获取用户信息)，否则报错
     * @return
     */
    @RequestMapping(value = "/index", method = { RequestMethod.GET, RequestMethod.POST })
    public ModelAndView index(HttpServletResponse request, HttpServletResponse response, String code, String state) {
        if (StringUtils.isBlank(code)) {
            ModelAndView view = new ModelAndView("weixin_auth_fail");
            view.addObject("ERROR_CODE", "2001");
            view.addObject("ERROR_MESSAGE", "未获取到授权码，请刷新重试");
            return view;
        }

        if (StringUtils.isBlank(state) || state.equalsIgnoreCase("state")) {
            state = WeixinAuthType.BASE.toString();
        }
        String openid = null;
        WeixinUserInfo weixinUserInfo = null;
        if (state.equalsIgnoreCase(WeixinAuthType.BASE.toString())) {
            ServiceResponse serviceResponse = weixinService.getOpenId(code);
            if (serviceResponse.isSuccess()) {
                openid = (String) serviceResponse.getData();
            } else {
                logger.error("Weixin auth faile-> code:" + code + " msg:" + serviceResponse.getMessage());

                ModelAndView view = new ModelAndView("weixin_auth_fail");
                view.addObject("ERROR_CODE", "2002");
                view.addObject("ERROR_MESSAGE", "未获取到用户信息，请刷新重试");
                return view;
            }
        } else if (state.equalsIgnoreCase(WeixinAuthType.USER_INFO.toString())) {
            ServiceResponse serviceResponse = weixinService.getWeixinUserInfo(code);
            if (serviceResponse.isSuccess()) {
                weixinUserInfo = (WeixinUserInfo) serviceResponse.getData();
                openid = weixinUserInfo.getOpenid();
                weixinService.saveWeixinUser(weixinUserInfo);
            } else {
                logger.error("Weixin auth faile-> code:" + code + " msg:" + serviceResponse.getMessage());

                ModelAndView view = new ModelAndView("weixin_auth_fail");
                view.addObject("ERROR_CODE", "2002");
                view.addObject("ERROR_MESSAGE", "未获取到用户信息，请刷新重试");
                return view;
            }
        } else {
            ModelAndView view = new ModelAndView("weixin_auth_fail");
            view.addObject("ERROR_CODE", "2003");
            view.addObject("ERROR_MESSAGE", "用户授权信息错误");
            return view;
        }

        if (openid == null) {
            ModelAndView view = new ModelAndView("weixin_auth_fail");
            view.addObject("ERROR_CODE", "2002");
            view.addObject("ERROR_MESSAGE", "未获取到用户信息，请刷新重试");
            return view;
        }

        ModelAndView view = new ModelAndView("weixin_redirect");
        view.addObject("openid", openid);
        view.addObject("user_info", JsonUtil.obj2Json(weixinUserInfo));
        return view;
    }
}
